import React, { useEffect, useState } from 'react';
import { Row, Col, Card, Statistic, Table, Tag, message } from 'antd';
import * as echarts from 'echarts';

// 添加组件内部样式
const styles = {
  chartContainer: {
    height: '100%',
    width: '100%',
    minHeight: '450px',
  }
};

// 定义接口类型
interface NetworkNode {
  id: string;
  name: string;
  value: number;
  category: number;
}

interface NetworkLink {
  source: string;
  target: string;
  value?: number;
}

interface NetworkStats {
  onlineNodes: number;
  totalNodes: number;
  avgLatency: number;
  bandwidth: number;
  packetLoss: number;
}

interface NodeStatus {
  key: string;
  nodeId: string;
  status: string;
  latency: string;
  bandwidth: string;
}

const NetworkMonitoring: React.FC = () => {
  const [chartInstance, setChartInstance] = useState<echarts.ECharts | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [networkStats, setNetworkStats] = useState<NetworkStats>({
    onlineNodes: 0,
    totalNodes: 0,
    avgLatency: 0,
    bandwidth: 0,
    packetLoss: 0
  });
  const [nodeStatusData, setNodeStatusData] = useState<NodeStatus[]>([]);

  // 获取网络拓扑数据
  const fetchNetworkData = async () => {
    setLoading(true);
    try {
      // 模拟API调用 - 在实际项目中替换为真实API
      // const response = await fetch('/api/network/topology');
      // const data = await response.json();
      
      // 模拟数据
      const mockData = {
        nodes: [
          { id: 'node1', name: '节点1', value: 20, category: 0 },
          { id: 'node2', name: '节点2', value: 15, category: 1 },
          { id: 'node3', name: '节点3', value: 25, category: 1 },
          { id: 'node4', name: '节点4', value: 18, category: 1 },
          { id: 'node5', name: '节点5', value: 22, category: 1 }
        ],
        links: [
          { source: 'node1', target: 'node2', value: 1 },
          { source: 'node1', target: 'node3', value: 2 },
          { source: 'node2', target: 'node4', value: 1 },
          { source: 'node3', target: 'node5', value: 3 },
          { source: 'node4', target: 'node5', value: 1 }
        ],
        stats: {
          onlineNodes: 8,
          totalNodes: 10,
          avgLatency: 25,
          bandwidth: 1.2,
          packetLoss: 0.1
        },
        nodeStatus: [
          {
            key: '1',
            nodeId: 'Node-001',
            status: '在线',
            latency: '20ms',
            bandwidth: '100Mbps',
          },
          {
            key: '2',
            nodeId: 'Node-002',
            status: '在线',
            latency: '15ms',
            bandwidth: '150Mbps',
          },
          {
            key: '3',
            nodeId: 'Node-003',
            status: '离线',
            latency: '0ms',
            bandwidth: '0Mbps',
          },
          {
            key: '4',
            nodeId: 'Node-004',
            status: '在线',
            latency: '18ms',
            bandwidth: '120Mbps',
          },
          {
            key: '5',
            nodeId: 'Node-005',
            status: '在线',
            latency: '22ms',
            bandwidth: '95Mbps',
          }
        ]
      };

      setNetworkStats(mockData.stats);
      setNodeStatusData(mockData.nodeStatus);
      
      // 更新图表
      updateChart(mockData.nodes, mockData.links);
    } catch (error) {
      console.error('获取网络拓扑数据失败:', error);
      message.error('获取网络拓扑数据失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 更新图表
  const updateChart = (nodes: NetworkNode[], links: NetworkLink[]) => {
    if (chartInstance) {
      const option = {
        animation: false,
        title: {
          text: '网络拓扑图',
          left: 'center'
        },
        tooltip: {
          formatter: '{b}: {c}'
        },
        legend: {
          data: ['主节点', '从节点'],
          orient: 'vertical',
          right: 10,
          top: 20
        },
        series: [{
          type: 'graph',
          layout: 'force',
          data: nodes.map(node => ({
            name: node.name,
            value: node.value,
            category: node.category,
            symbolSize: node.value,
            itemStyle: {
              color: node.category === 0 ? '#FF6B3B' : '#626c91'
            }
          })),
          links: links.map(link => ({
            source: link.source,
            target: link.target,
            lineStyle: {
              width: link.value ? link.value : 1,
              curveness: 0.3
            }
          })),
          categories: [
            { name: '主节点' },
            { name: '从节点' }
          ],
          roam: true,
          label: {
            show: true,
            position: 'right',
            formatter: '{b}'
          },
          force: {
            repulsion: 200,
            edgeLength: 120
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {
              width: 4
            }
          }
        }]
      };
      chartInstance.setOption(option);
    }
  };

  useEffect(() => {
    const chartDom = document.getElementById('networkChart');
    if (chartDom) {
      const chart = echarts.init(chartDom);
      setChartInstance(chart);
      
      // 添加窗口大小变化监听，解决自适应问题
      const handleResize = () => {
        chart.resize();
      };
      window.addEventListener('resize', handleResize);
      
      return () => {
        window.removeEventListener('resize', handleResize);
        chart.dispose();
      };
    }
  }, []);

  // 在组件挂载后获取数据
  useEffect(() => {
    if (chartInstance) {
      fetchNetworkData();
      
      // 设置定时刷新（每30秒刷新一次）
      const intervalId = setInterval(fetchNetworkData, 30000);
      
      return () => {
        clearInterval(intervalId);
      };
    }
  }, [chartInstance]);

  const columns = [
    {
      title: '节点ID',
      dataIndex: 'nodeId',
      key: 'nodeId',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '在线' ? 'success' : 'error'}>
          {status}
        </Tag>
      ),
    },
    {
      title: '延迟',
      dataIndex: 'latency',
      key: 'latency',
    },
    {
      title: '带宽',
      dataIndex: 'bandwidth',
      key: 'bandwidth',
    },
  ];

  return (
    <div className="p-6">
      <Row gutter={[16, 16]} className="mb-6">
        <Col span={6}>
          <Card>
            <Statistic 
              title="在线节点" 
              value={networkStats.onlineNodes} 
              suffix={`/ ${networkStats.totalNodes}`} 
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均延迟" 
              value={networkStats.avgLatency} 
              suffix="ms" 
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="网络带宽" 
              value={networkStats.bandwidth} 
              suffix="Gbps" 
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="数据包丢失率" 
              value={networkStats.packetLoss} 
              suffix="%" 
              loading={loading}
            />
          </Card>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col span={16}>
          <Card title="网络拓扑" className="h-[500px]" loading={loading}>
            <div id="networkChart" style={styles.chartContainer}></div>
          </Card>
        </Col>
        <Col span={8}>
          <Card title="节点状态" className="h-[500px] overflow-auto" loading={loading}>
            <Table columns={columns} dataSource={nodeStatusData} pagination={false} />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default NetworkMonitoring; 